package com.baizhi.controller;

import com.baizhi.annotation.LogAnnotation;
import com.baizhi.service.UserService;
import com.baizhi.util.ThreadPollUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

@Controller
@RequestMapping("userEcharts")
public class UserEchartsController {

    @Autowired
    private UserService userService;

    //查询全部用户统计（优化后）
    @LogAnnotation(content = "查询全部用户统计（优化后）",type = "select")
    @ResponseBody
    @RequestMapping("selectAll2")
    public Map showAll() throws InterruptedException {
        long time1 = System.currentTimeMillis();
        //1.创建三个子线程 初始化计数器
        Map map = new HashMap();
        CountDownLatch countDownLatch = new CountDownLatch(3);
        //2、创建人物提交线程池
        ThreadPollUtil.executor.submit(new Runnable() {
            @Override
            public void run() {
                //注册量
                List<Map> listSex = userService.showBySex();
                map.put("sex",listSex);
                //计数器减一
                countDownLatch.countDown();
            }
        });
        ThreadPollUtil.executor.submit(new Runnable() {
            @Override
            public void run() {
                //根据时间查询
                List<Map> listTime = new ArrayList<>();
                List<Map> list1 = userService.showByTime(1, 7);
                List<Map> list2 = userService.showByTime(7,14);
                List<Map> list3 = userService.showByTime(14,21);
                list1.get(0).put("name","过去一周");
                list2.get(0).put("name","过去两周");
                list3.get(0).put("name","过去三周");
                listTime.add(list1.get(0));
                listTime.add(list2.get(0));
                listTime.add(list3.get(0));
                map.put("time",listTime);
                //计数器减一
                countDownLatch.countDown();
            }
        });
        ThreadPollUtil.executor.submit(new Runnable() {
            @Override
            public void run() {
                //根据省份查询
                List<Map> listProvince = userService.showByProvince();
                map.put("province",listProvince);
                //计数器减一
                countDownLatch.countDown();
            }
        });

        /**
         * 通过调用await方法让主线程等待子线程
         */
        countDownLatch.await();
        long time2 = System.currentTimeMillis();
        System.out.println("time1 = " + time1);
        System.out.println("time2 = " + time2);
        System.out.println(time2-time1+"ms");

        return map;
    }
}
